<?php
/**
 * Library Of Shared Code (LOSC)
 *
 * LICENSE
 *
 * This source file is subject to the New BSD License that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @category   LOSC Framework
 * @package    Validate
 * @copyright  Copyright (c) 2008 Robin Skoglund (http://robinsk.net/)
 * @license    http://creativecommons.org/licenses/BSD/  New BSD License
 */

/**
 * Validator for checking that a string is a valid locale
 *
 * @category   LOSC Framework
 * @package    Validate
 * @copyright  Copyright (c) 2008 Robin Skoglund (http://robinsk.net/)
 * @license    http://creativecommons.org/licenses/BSD/  New BSD License
 */
class Losc_Validate_Language extends Zend_Validate_Abstract
{
    const NOT_VALID_LANG = 'notValidLanguage';

    /**
     * Error messages
     * 
     * @var array
     */
    protected $_messageTemplates = array(
        self::NOT_VALID_LANG => '"%value%" is not a valid language'
    );
    
    /**
     * Creates validator
     *
     */
    public function __construct()
    {
        
    }
    
    /**
     * Defined by Zend_Validate_Interface
     *
     * Returns true if and only if $value is a valid locale
     * 
     * @param  string $value
     * @return boolean
     * @throws Losc_Exception
     */
    public function isValid($value)
    {
        $this->_setValue($value);
        
        if (!Zend_Registry::isRegistered('Zend_Translate')) {
            $msg = 'Unable to find translator';
            throw new Losc_Exception($msg);
        }
        
        $t = Zend_Registry::get('Zend_Translate');
        if ($t instanceof Zend_Translate) {
            $t = $t->getAdapter();
        } elseif (!$t instanceof Zend_Translate_Adapter) {
            $msg = 'Unable to find translator';
            throw new Losc_Exception($msg);
        }
        
        $validLanguages = $t->getList();

        if (!in_array($value, $validLanguages)) {
            $this->_error();
            return false;
        }

        return true;
    }
}
